// pages/mine/mine.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    signInStatus: null,
    planTime: 0,
    planList: null,
    planShow: false,
    planMaskShow: false,
    planTop: 0,
    planHint: false,
    planValue: null,
    planRepeat: true,
    dateStart: null,
    dateEnd: null,
    repeatDateList: ['每天','每周一','每周二','每周三','每周四','每周五','每周六','每周日'],
    selectRepeatIndex: 0,
    popUpType: 'text',
    popUpShow: false,
    popUpTitle: '弹窗标题',
    popUpData: null
  },

  /**
   * 初始化签到信息
   */
  initSignInStatus(){
    var that = this;
    // 赋值已有数据
    that.setData({
      signInStatus: app.globalData.signInStatus
    });
    // 监听全局变量变化
    app.watch('signInStatus',function(value){
      that.setData({
        signInStatus: value
      });
    });
    // 初始化setter
    app.globalData.signInStatus = that.data.signInStatus;
  },

  /**
   * 初始化行程提醒信息
   */
  initPlanList(){
    var that = this;
    // 赋值已有数据
    that.setData({
      planList: app.globalData.planList
    });
    // 监听全局变量变化
    app.watch('planList',function(value){
      that.setData({
        planList: value
      });
    });
    // 初始化setter
    app.globalData.planList = that.data.planList;
  },

  /**
   * 初始化订阅次数
   */
  initPlanTime(){
    var that = this;
    // 赋值已有数据
    that.setData({
      planTime: app.globalData.planTime
    });
    // 监听全局变量变化
    app.watch('planTime',function(value){
      that.setData({
        planTime: value
      });
    });
    // 初始化setter
    app.globalData.planTime = that.data.planTime;
  },

  /**
   * 签到按钮
   */
  signIn(){
    wx.navigateTo({
      url: '/pages/signIn/signIn'
    });
  },

  /**
   * 行程列表项-触摸开始事件
   */
  planTouchStart(e){
    var planId = e.currentTarget.dataset.planid;
    if(!planId) return;
    this.setData({
      pageX: e.changedTouches[0].pageX,
      pageY: e.changedTouches[0].pageY,
    });
  },
  /**
   * 行程列表项-触摸结束事件
   */
  planTouchEnd(e){
    var planId = e.currentTarget.dataset.planid;
    if(!this.data.pageX&&!this.data.pageY&&!planId) return;
    var moveX = e.changedTouches[0].pageX-this.data.pageX;
    var moveY = Math.abs(e.changedTouches[0].pageY-this.data.pageY);
    if(moveX<-30&&moveY<70){
      let planList = this.data.planList;
      for(var t of planList){
        if(t.planId == planId){
          t.deleteBtn = true;
          break;
        }
      }
      app.globalData.planList = planList;
    }else if(moveX>30&&moveY<70){
      let planList = this.data.planList;
      for(var t of planList){
        if(t.planId == planId){
          t.deleteBtn = false;
          break;
        }
      }
      app.globalData.planList = planList;
    }
  },

  /**
   * 删除行程
   */
  deletePlan(e){
    if(!e.currentTarget.dataset.planid) return;
    // 系统弹窗-确认删除
    wx.showModal({
      content: '确定删除行程么？',
      showCancel: true,
      success: res=>{
        // 确认
        if(res.confirm){
          wx.showLoading({
            title: '删除中',
            mask: true
          });
          // 调用删除行程提醒云函数
          wx.cloud.callFunction({
            name: 'deletePlan',
            data: {
              planId: e.currentTarget.dataset.planid
            },
            success: res=>{
              console.log(res,'删除行程提醒');
              this.setData({
                popUpType: 'text',
                popUpShow: true,
                popUpTitle: '行程提醒',
                popUpData: [
                    {
                      style: '',
                      value: res.result&&res.result.code?res.result.msg:'删除失败，请重试！'
                    }
                  ]
              });
              // 刷新列表项
              if(res.result&&res.result.code){
                let data = res.result.data;
                data.sort((a,b)=>b.id-a.id);
                app.globalData.planList = data;
              }
            },
            fail: console.error,
            complete: ()=>{
              wx.hideLoading();
            }
          });
        }
      }
    });
    
  },

  /**
   * 点击新建行程窗口的mask区域
   */
  clickPlanMask(e){
    if(e.target.dataset.name=='mask'){
      this.closePlan();
    }
  },

  /**
   * 关闭新建行程窗口
   */
  closePlan(){
    clearTimeout(this.data.showT);
    // 动画播放完再隐藏
    this.setData({
      planShow: false,
      showT: setTimeout(()=>{
        this.setData({
          planMaskShow: false
        });
      },400)
    });
  },
  /**
   * 打开新建行程窗口
   */
  openPlan(){
    clearTimeout(this.data.showT);
    this.updateTime();
    // 打开动画
    this.setData({
      planHint: false,
      planMaskShow: true,
      showT: setTimeout(()=>{
        this.setData({
          planShow: true
        });
      },10)
    });
  },

  /**
   * plan输入框得到焦点
   */
  planFocus(e){
    this.setData({
      planHint: false
    });
  },
  /**
   * plan输入框失去焦点
   */
  planBlur(e){
    if(!e.detail.value){
      this.setData({
        planHint: true
      });
    }
  },
  /**
   * plan输入框内容改变
   */
  planInput(e){
    this.setData({
      planValue: e.detail.value
    });
  },

  /**
   * 重复提醒单选框事件
   */
  radioChange: function (e){
    if(e.detail.value=='yes'){
      this.setData({
        planRepeat: true
      });
    }else if(e.detail.value=='no'){
      this.updateTime();
      this.setData({
        planRepeat: false
      });
    }
  },

  /**
   * 更新当前日期
   */
  updateTime(){
    var now = new Date();
    var year = now.getFullYear().toString();
    var month = (now.getMonth()+1).toString();
    month = month.length==1?'0'+month:month;
    var day = now.getDate().toString();
    day = day.length==1?'0'+day:day;

    var twoM = new Date(now.getTime()+120*1000);// 两分钟后
    var hour = twoM.getHours().toString();
    hour = hour.length==1?'0'+hour:hour;
    var minute = twoM.getMinutes().toString();
    minute = minute.length==1?'0'+minute:minute;

    var end = new Date(now.getTime()+100*24*3600*1000);// 100天后
    var endYear = end.getFullYear().toString();
    var endMonth = (end.getMonth()+1).toString();
    endMonth = endMonth.length==1?'0'+endMonth:endMonth;
    var endDay = end.getDate().toString();
    endDay = endDay.length==1?'0'+endDay:endDay;
    this.setData({
      selectDay: day,
      selectMonth: month,
      selectYear: year,
      nowHour: hour,
      nowMinute: minute,
      selectHour: hour,
      selectMinute: minute,
      dateStart: year+'-'+month+'-'+day,
      dateEnd: endYear+'-'+endMonth+'-'+endDay
    });
  },

  /**
   * 更改提醒日期
   */
  changeDate(e){
    var selectValue = e.detail.value.split('-');
    this.setData({
      selectYear: selectValue[0],
      selectMonth: (selectValue[1].length==1?'0':'')+selectValue[1],
      selectDay: (selectValue[2].length==1?'0':'')+selectValue[2]
    });
    // 若选择的是今天则更新时间
    if(this.data.selectYear+'-'+this.data.selectMonth+'-'+this.data.selectDay==this.data.dateStart) this.updateTime();
    console.log(selectValue)
  },

  /**
   * 更改重复提醒日期
   */
  changeRepeatDate(e){
    var index = e.detail.value;
    this.setData({
      selectRepeatIndex: index
    });
    console.log(index)
  },

  /**
   * 更改提醒时间
   */
  changeTime(e){
    var selectValue = e.detail.value.split(':');
    this.setData({
      selectHour: (selectValue[0].length==1?'0':'')+selectValue[0],
      selectMinute: (selectValue[1].length==1?'0':'')+selectValue[1]
    });
  },

  /**
   * 点击提交行程
   */
  clickSubmit(){
    if(!this.data.planValue){
      this.setData({
        planHint:true
      });
      return;
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    });
    // 订阅一次消息
    this.addMessage(()=>{
      // 后端请求增加行程
      this.newPlan();
    });
  },

  /**
   * 订阅一次消息
   */
  addMessage(callback){
    // 请求消息订阅
    wx.requestSubscribeMessage({
      tmplIds: ['Uh2sp9Y4qU_EW9fnywG7mheCJ3MBJU1ZJj3m_N6s9hU'],
      success: res=>{
        console.log(res)
        if(res['Uh2sp9Y4qU_EW9fnywG7mheCJ3MBJU1ZJj3m_N6s9hU']=='accept'){
          // 成功回调
          if(callback) callback();
        }else{
          // 获取授权信息
          wx.getSetting({
            withSubscriptions: true,
            success: res=>{
              console.log(res,'获取授权信息')
              // 授权订阅 及授权行程模板
              let isAuth = res.subscriptionsSetting.mainSwitch&&(['reject','ban'].indexOf(res.subscriptionsSetting.itemSettings&&res.subscriptionsSetting.itemSettings['Uh2sp9Y4qU_EW9fnywG7mheCJ3MBJU1ZJj3m_N6s9hU'])==-1);
              // 若未授权
              if(!isAuth){
                // 再次请求授权
                this.authorizeAgain();
              }
            },
            complete: res=>{
              wx.hideLoading();
            }
          });
        }
      },fail: err=>{
        // console.log(err,'订阅失败');
        wx.hideLoading();
        // 再次请求授权
        this.authorizeAgain();
      }
    })
  },

  /**
   * 再次授权
   */
  authorizeAgain(){
    // 系统弹窗-引导再次授权
    wx.showModal({
      content: '检测到您没有授权消息订阅，是否前往后台进行设置？',
      showCancel: true,
      success: res=>{
        // 确认再次授权
        if(res.confirm){
          // 打开授权设置页面
          wx.openSetting({
            withSubscriptions: true,
            success: res=>{
              console.log(res,'后台回调');
              // 授权订阅 及授权行程模板
              let isAuth = res.subscriptionsSetting.mainSwitch&&(['reject','ban'].indexOf(res.subscriptionsSetting.itemSettings&&res.subscriptionsSetting.itemSettings['Uh2sp9Y4qU_EW9fnywG7mheCJ3MBJU1ZJj3m_N6s9hU'])==-1);
              // 自定义弹窗提示
              this.setData({
                popUpType: 'text',
                popUpShow: true,
                popUpTitle: '消息订阅授权',
                popUpData: [
                    {
                      style: '',
                      value: isAuth?'授权成功':'授权失败'
                    }]
              });
            }
          })
        }
      }
    });
  },

  /**
   * 增加一次订阅次数
   */
  addPlanTime(){
    wx.showLoading({
      title: '订阅中',
      mask: true
    });
    // 订阅一次消息
    this.addMessage(()=>{
      // 后端增加次数
      // 调用增加订阅次数云函数
      wx.cloud.callFunction({
        name: 'addPlanTime',
        success: res=>{
          console.log(res,'订阅一次消息');
          this.setData({
            popUpType: 'text',
            popUpShow: true,
            popUpTitle: '订阅消息',
            popUpData: [
                {
                  style: '',
                  value: res.result&&res.result.code?'增加订阅次数成功！':'增加订阅次数失败，请重试！'
                }
              ]
          });
          // 提交成功清空填写
          if(res.result&&res.result.code){
            let planTime = res.result.planTime;
            app.globalData.planTime = planTime;
          }
        },
        fail: console.error,
        complete: ()=>{
          wx.hideLoading();
        }
      });
    });
  },

  /**
   * 新建行程提醒
   */
  newPlan(){
    var obj = {
      title: this.data.planValue,
      hour: this.data.selectHour,
      minute: this.data.selectMinute
    };
    if(this.data.planRepeat){
      if(this.data.selectRepeatIndex!=0){
        obj['dayOfWeek'] = this.data.selectRepeatIndex;
      }
    }else{
      obj['year'] = this.data.selectYear;
      obj['month'] = this.data.selectMonth;
      obj['dayOfMonth'] = this.data.selectDay;
    }
    // 调用新建行程提醒云函数
    wx.cloud.callFunction({
      name: 'newPlan',
      data:obj,
      success: res=>{
        console.log(res,'新建行程提醒');
        this.setData({
          popUpType: 'text',
          popUpShow: true,
          popUpTitle: '行程提醒',
          popUpData: [
              {
                style: '',
                value: res.result&&res.result.code?'新建提醒成功！':'新建提醒失败，请重试！'
              }
            ]
        });
        // 提交成功清空填写
        if(res.result&&res.result.code){
          let data = res.result.data;
          data.sort((a,b)=>b.id-a.id);
          app.globalData.planList = data;
          app.globalData.planTime = res.result.planTime;
          this.setData({
            clearValue: '',
            planValue: null,
            planRepeat: true,
            planShow: false,
            planMaskShow: false,
            planTop: 0,
            selectRepeatIndex: 0
          });
        }
      },
      fail: console.error,
      complete: ()=>{
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.updateTime();
    // 初始化行程提醒信息
    this.initPlanList();
    // 初始化订阅次数
    this.initPlanTime();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 初始化签到信息-全局双向绑定
    this.initSignInStatus();
    

    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})